package com.kbt.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.*;
import android.widget.*;
import com.android.volley.Request;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.ShopFenLeiBean;
import com.kbt.model.data.ShopFenLeiListBean;
import com.kbt.model.holder.GoodItemInfoHolder;
import com.kbt.net.RequestManager;
import com.kbt.ui.AddCarPopWindow;
import com.kbt.util.data.StaticData;
import com.kbt.util.utils.ImageManager;
import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.SetingImage;
import com.kbt.util.utils.Utils;
import com.readystatesoftware.viewbadger.BadgeView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2015/8/5.
 */
public class NewGoodsListActivity extends FragmentActivity implements RequestManager.ResponseInterface{


    private RadioGroup rg;
    private BadgeView badgeView;

    private RequestManager mRequestManager;
    private Map<String, Object> map =null;
    private ShopFenLeiListBean shopFenLeiListBean;
    private List<ShopFenLeiBean> shopFenLeiBeans = new ArrayList<ShopFenLeiBean>();
    private GoodsListAdapter goodAdapter;
    private String tag;
    private LoadingDialog mProgress;
    private  LinearLayout noOrderLin;
    private GridView gv;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.new_goods_list_layout);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);
        ImageView returnImg =(ImageView) findViewById(R.id.return_btn);

        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.getInstance().removeActivity(NewGoodsListActivity.this);
                finish();
            }
        });
        Intent intent =getIntent();
        tag = intent.getStringExtra("tag");
        String name = intent.getStringExtra("name");
        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText(name);
        BaseApplication.getInstance().addActivity(NewGoodsListActivity.this);
        noOrderLin = (LinearLayout) findViewById(R.id.noOrderLin);
        rg = (RadioGroup) findViewById(R.id.tabRadioGroup);
        gv=(GridView)findViewById(R.id.GridView01);
        RadioButton home = (RadioButton)findViewById(R.id.gl_home_radio);
        RadioButton car = (RadioButton)findViewById(R.id.gl_car_radio2);
        RadioButton my = (RadioButton)findViewById(R.id.gl_my_radio);
        RadioButton news = (RadioButton) findViewById(R.id.gl_news_radio);
        home.setOnClickListener(new NavItemOnclickListener());
        car.setOnClickListener(new NavItemOnclickListener());
        my.setOnClickListener(new NavItemOnclickListener());
        news.setOnClickListener(new NavItemOnclickListener());
        home.setChecked(false);
        TextView carCountView = (TextView)findViewById(R.id.carCountView);
        badgeView = new BadgeView(this,carCountView);
        setCarCount(BaseApplication.getInstance().shopType);
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, Object>();
        //设置GridView的行数
        gv.setNumColumns(2);
        goodAdapter = new GoodsListAdapter(this.getApplicationContext(),shopFenLeiBeans);
        gv.setAdapter(goodAdapter);
        httpFenlei();
        BaseApplication.getInstance().addActivitytwo(NewGoodsListActivity.this);
    }



    private void httpFenlei() {
        showProgress();
        if(Utils.isNetworkAvailable(NewGoodsListActivity.this)){
            mRequestManager.requestGet(Request.Method.GET, Constants.ServiceInterFace.shopFenLeiURL+tag, Constants.RequestTag.shopFenLeiTag, map, ShopFenLeiListBean.class);
        }else{
            Toast.makeText(NewGoodsListActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }


    //转向主页面
    private void goToStoreActivity(int ViewId) {
        BaseApplication.getInstance().currentItem=ViewId;
        BaseApplication.getInstance().removeActivity(NewGoodsListActivity.this);
        finish();
    }

    public void setCarCount(int buyCount) {
        if(buyCount==0){
            badgeView.hide();
            return;
        }
        String badgeText = String.valueOf(badgeView.getText());
        badgeText = "".equals(badgeText) ? "0" : badgeText;
        int carCount = Integer.parseInt(badgeText);
        badgeView.setText(String.valueOf(carCount + buyCount));
        badgeView.show();
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        stopProgress();
        if (tag == Constants.RequestTag.shopFenLeiTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                shopFenLeiListBean = (ShopFenLeiListBean) parsedGSON;
                // 判断是否是有数据
                if (shopFenLeiListBean.getResult().equals("success")) {// 成功
                    if (shopFenLeiListBean.getData().size()>0) {//获取到数据
                        shopFenLeiBeans = shopFenLeiListBean.getData();
                        goodAdapter.setList(shopFenLeiBeans);
                        goodAdapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.GONE);
                        gv.setVisibility(View.VISIBLE);
                    }else{
                        shopFenLeiBeans.clear();
                        goodAdapter.setList(shopFenLeiBeans);
                        goodAdapter.notifyDataSetChanged();
                        noOrderLin.setVisibility(View.VISIBLE);
                        gv.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        stopProgress();
        Toast.makeText(NewGoodsListActivity.this, R.string.noWangluo, Toast.LENGTH_SHORT).show();
    }

    private class GoodsListAdapter extends BaseAdapter{
        Context context;
        List<ShopFenLeiBean> list;

        public GoodsListAdapter(Context _context, List<ShopFenLeiBean> _list) {
            this.list = _list;
            this.context = _context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        /**
         * 再次赋值
         *
         * @param mlist
         */
        public void setList(List<ShopFenLeiBean> mlist) {
            list = mlist;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           GoodItemInfoHolder itemHolder;
            if(convertView == null){
                itemHolder = new GoodItemInfoHolder();
                LayoutInflater layoutInflater = LayoutInflater.from(context);
                convertView = layoutInflater.inflate(R.layout.new_goods_fl_item_info_layout, null);
                itemHolder.setGoodImg((ImageView) convertView.findViewById(R.id.goodImg));
                itemHolder.setGoodTitle((TextView) convertView.findViewById(R.id.goodTitle));
                itemHolder.setNewPriceView((TextView) convertView.findViewById(R.id.goodNewPrice));
                itemHolder.setOldPriceView((TextView) convertView.findViewById(R.id.GoodOldPrice));
                itemHolder.setCarImg((ImageView) convertView.findViewById(R.id.GoodAddCar));
                itemHolder.setShouwan((ImageView) convertView.findViewById(R.id.shouwan));
                itemHolder.setKaiqiang((TextView) convertView.findViewById(R.id.kaiqiang));
                convertView.setTag(itemHolder);
            }else{
                itemHolder = (GoodItemInfoHolder)convertView.getTag();
            }

            final ShopFenLeiBean newGood= list.get(position);
            itemHolder.getNewPriceView().setText("￥"+newGood.getGoods_new_price());
            itemHolder.getGoodTitle().setText(newGood.getGoods_title());
            itemHolder.getOldPriceView().setText("￥"+newGood.getGoods_price());
            itemHolder.getOldPriceView().getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            String url = newGood.getGoods_icon();
            int screenWidth =getWindowManager().getDefaultDisplay().getWidth()/2-10;
            SetingImage.setImageHeightWidth(screenWidth,url,itemHolder.getGoodImg());
            ImageManager.imageLoader.displayImage(Constants.ServiceInterFace.imageURL + newGood.getGoods_icon(), itemHolder.getGoodImg(), ImageManager.getOptions(
                    R.drawable.loadings, R.drawable.loadings));

            itemHolder.getGoodImg().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(NewGoodsListActivity.this, GoodInfoActivity.class);
                    intent.putExtra("shopId", newGood.getGoods_id() + "");
                    startActivity(intent);
                }
            });

            int screenWidth2 = getWindowManager().getDefaultDisplay().getWidth()/4;
            SetingImage.setImageHeightWidthTwo(screenWidth2,url,itemHolder.getShouwan());

            if(Integer.parseInt(newGood.getStore_counts())<=0){
                itemHolder.getCarImg().setVisibility(View.INVISIBLE);
                itemHolder.getShouwan().setBackgroundResource(R.drawable.shouwan);
                itemHolder.getShouwan().setVisibility(View.VISIBLE);
            }else{
                if(getTime(newGood.getStart_time())){
                    itemHolder.getCarImg().setVisibility(View.GONE);
                    itemHolder.getKaiqiang().setVisibility(View.VISIBLE);
                    itemHolder.getNewPriceView().setTextColor(Color.rgb(20,168,106));
                    itemHolder.getShouwan().setVisibility(View.GONE);
                    itemHolder.getShouwan().setBackgroundResource(R.drawable.kaiqiang);
                }else{
                    itemHolder.getKaiqiang().setVisibility(View.GONE);
                    itemHolder.getCarImg().setVisibility(View.VISIBLE);
                    itemHolder.getShouwan().setVisibility(View.GONE);
                    itemHolder.getNewPriceView().setTextColor(Color.rgb(199, 0, 11));
                }
            }

            itemHolder.getCarImg().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(BaseApplication.getInstance().isLogin()){

                        AddCarPopWindow menuWindow = new AddCarPopWindow(NewGoodsListActivity.this,
                                StaticData.PopWindowFromGoodFl,newGood.getGoods_id(),newGood.getGoods_icon(),newGood.getGoods_new_price(),newGood.getStore_counts());
                        //显示窗口
                        menuWindow.showAtLocation(NewGoodsListActivity.this.findViewById(R.id.goods_listView),
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                    }else{
                        Intent intent = new Intent(context,LoginActivity.class);
                        startActivity(intent);
                        BaseApplication.getInstance().removeActivity(NewGoodsListActivity.this);
//                        finish();
                    }
                }
            });
            itemHolder.getGoodTitle().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(NewGoodsListActivity.this, GoodInfoActivity.class);
                    intent.putExtra("shopId", newGood.getGoods_id() + "");
                    startActivity(intent);
                }
            });

            return convertView;
        }

    }



    private class NavItemOnclickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.gl_home_radio:
                    goToStoreActivity(StaticData.INDEX_HOME);
                    break;
                case R.id.gl_car_radio2:
                    goToStoreActivity(StaticData.INDEX_CAR);
                    break;
                case R.id.gl_my_radio:
                    goToStoreActivity(StaticData.INDEX_MY);
                    break;
                case R.id.gl_news_radio:
                    goToStoreActivity(StaticData.INDEX_NEWS);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * progressDialog的展示
     */
    public void showProgress() {
        if (mProgress == null) {
            mProgress = new LoadingDialog(NewGoodsListActivity.this,"");
            mProgress.setCancelable(true);
            mProgress.show();

        } else {
            if (mProgress.isShowing()) {
                stopProgress();
            } else {
                mProgress.show();
            }
        }
    }


    /**
     * progressDialog的消失
     */
    public void stopProgress() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }

    /**
     * 得到时间差
     */
    private  boolean getTime(String time2){

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            Date d1 = df.parse(time2);
            Date d2 = df.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            long diff = d1.getTime() - d2.getTime();
            if(diff>0){
              return true;//购物车不显示
            }else{
              return false;
            }

        }
        catch (Exception e)
        {
        }
        return false;
    }


}
